import requests

from Crypto.Cipher import AES

import re



file = open('./聯係.m3u8', 'r', encoding='utf8')

file_text = file.read()

file.close()


parths = 'URI="(.*?)"'

KEYURL = re.findall(parths, file_text)[0]
print("KEY匹配完成")
# 讀取並獲取key值
KEY = requests.get(url=KEYURL).content

# 獲取iv
IV = b"0000000000000000"
# IV = re.findall('IV=(.*?)\n', file_text)[0]

for obj in file_text.split('\n'):
    if obj.count("#") == 0:
        # 下載ts
        print("開始下載ts")
        ts_data = requests.get(url=obj, ).content
        print("下載ts完成, 正在解密")
        aes = AES.new(key=KEY, mode=AES.MODE_CBC, iv=IV)
        ts_data = aes.decrypt(ts_data)
        print("解密完成")
        # 獲取文件名
        file_name = obj.split('-')[-1] + ".ts"
        with open(file_name, 'wb') as e:
            e.write(ts_data)
        break

